package com.personalink.input.service;

import com.personalink.common.dto.ChatRequest;
import com.personalink.input.dto.InputProcessResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文本处理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TextProcessService {
    
    // 情感词典（简化版）
    private static final Set<String> POSITIVE_WORDS = Set.of(
            "开心", "高兴", "快乐", "喜欢", "爱", "好", "棒", "赞", "优秀", "满意",
            "happy", "good", "great", "love", "like", "excellent", "wonderful", "amazing"
    );
    
    private static final Set<String> NEGATIVE_WORDS = Set.of(
            "难过", "伤心", "生气", "愤怒", "讨厌", "坏", "糟糕", "失望", "痛苦", "不满",
            "sad", "angry", "bad", "terrible", "hate", "disappointed", "upset", "frustrated"
    );
    
    // 意图识别关键词
    private static final Map<String, Set<String>> INTENT_KEYWORDS = Map.of(
            "medical", Set.of("头痛", "发烧", "咳嗽", "感冒", "病", "疼", "不舒服", "症状", "医生", "药"),
            "cooking", Set.of("做菜", "菜谱", "食谱", "烹饪", "料理", "食材", "怎么做", "cooking", "recipe"),
            "emotional", Set.of("心情", "情感", "感受", "倾诉", "聊天", "陪伴", "孤独", "压力", "焦虑")
    );
    
    // 实体识别模式
    private static final Map<String, Pattern> ENTITY_PATTERNS = Map.of(
            "PHONE", Pattern.compile("1[3-9]\\d{9}"),
            "EMAIL", Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"),
            "DATE", Pattern.compile("\\d{4}[-/年]\\d{1,2}[-/月]\\d{1,2}[日]?"),
            "TIME", Pattern.compile("\\d{1,2}[：:]\\d{2}")
    );
    
    /**
     * 处理文本输入
     */
    public InputProcessResult processText(ChatRequest request) {
//        String text = request.getTextContent();
        String text = request.getText();
        if (text == null || text.trim().isEmpty()) {
            throw new IllegalArgumentException("文本内容不能为空");
        }
        
        log.debug("开始处理文本: {}", text.substring(0, Math.min(text.length(), 100)));
        
        // 文本预处理
        String processedText = preprocessText(text);
        
        // 文本分析
        InputProcessResult.TextAnalysis analysis = analyzeText(processedText);
        
        return InputProcessResult.builder()
                .userId(request.getUserId())
                .sessionId(request.getSessionId())
                .inputType("text")
                .processedText(processedText)
                .textAnalysis(analysis)
                .processedAt(System.currentTimeMillis())
                .build();
    }
    
    /**
     * 文本预处理
     */
    private String preprocessText(String text) {
        // 去除多余空白字符
        text = text.trim().replaceAll("\\s+", " ");
        
        // 过滤敏感内容（简化版）
        text = filterSensitiveContent(text);
        
        return text;
    }
    
    /**
     * 过滤敏感内容
     */
    private String filterSensitiveContent(String text) {
        // 简化的敏感词过滤
        Set<String> sensitiveWords = Set.of("暴力", "色情", "政治");
        
        for (String word : sensitiveWords) {
            if (text.contains(word)) {
                log.warn("检测到敏感内容: {}", word);
                text = text.replace(word, "***");
            }
        }
        
        return text;
    }
    
    /**
     * 文本分析
     */
    private InputProcessResult.TextAnalysis analyzeText(String text) {
        return InputProcessResult.TextAnalysis.builder()
                .sentiment(analyzeSentiment(text))
                .intent(recognizeIntent(text))
                .keywords(extractKeywords(text))
                .entities(extractEntities(text))
                .detectedLanguage(detectLanguage(text))
                .qualityScore(calculateQualityScore(text))
                .build();
    }
    
    /**
     * 情感分析
     */
    private InputProcessResult.SentimentResult analyzeSentiment(String text) {
        int positiveCount = 0;
        int negativeCount = 0;
        
        String[] words = text.toLowerCase().split("\\s+");
        
        for (String word : words) {
            if (POSITIVE_WORDS.contains(word)) {
                positiveCount++;
            } else if (NEGATIVE_WORDS.contains(word)) {
                negativeCount++;
            }
        }
        
        String label;
        double score;
        
        if (positiveCount > negativeCount) {
            label = "positive";
            score = Math.min(0.5 + (positiveCount - negativeCount) * 0.1, 1.0);
        } else if (negativeCount > positiveCount) {
            label = "negative";
            score = Math.min(0.5 + (negativeCount - positiveCount) * 0.1, 1.0);
        } else {
            label = "neutral";
            score = 0.5;
        }
        
        // 构建情感详情
        Map<String, Double> emotions = new HashMap<>();
        emotions.put("joy", positiveCount > 0 ? 0.7 : 0.3);
        emotions.put("sadness", negativeCount > 0 ? 0.7 : 0.3);
        emotions.put("anger", text.contains("生气") || text.contains("愤怒") ? 0.8 : 0.2);
        emotions.put("fear", text.contains("害怕") || text.contains("恐惧") ? 0.8 : 0.2);
        
        return InputProcessResult.SentimentResult.builder()
                .label(label)
                .score(score)
                .emotions(emotions)
                .build();
    }
    
    /**
     * 意图识别
     */
    private String recognizeIntent(String text) {
        String lowerText = text.toLowerCase();
        
        for (Map.Entry<String, Set<String>> entry : INTENT_KEYWORDS.entrySet()) {
            String intent = entry.getKey();
            Set<String> keywords = entry.getValue();
            
            for (String keyword : keywords) {
                if (lowerText.contains(keyword.toLowerCase())) {
                    log.debug("识别到意图: {} (关键词: {})", intent, keyword);
                    return intent;
                }
            }
        }
        
        return "general";
    }
    
    /**
     * 关键词提取
     */
    private List<String> extractKeywords(String text) {
        // 简化的关键词提取
        String[] words = text.split("\\s+");
        Set<String> keywords = new HashSet<>();
        
        // 过滤停用词
        Set<String> stopWords = Set.of("的", "了", "在", "是", "我", "你", "他", "她", "它", 
                "and", "the", "is", "are", "was", "were", "a", "an");
        
        for (String word : words) {
            word = word.trim().toLowerCase();
            if (word.length() > 1 && !stopWords.contains(word)) {
                keywords.add(word);
            }
        }
        
        return new ArrayList<>(keywords);
    }
    
    /**
     * 实体识别
     */
    private List<InputProcessResult.NamedEntity> extractEntities(String text) {
        List<InputProcessResult.NamedEntity> entities = new ArrayList<>();
        
        for (Map.Entry<String, Pattern> entry : ENTITY_PATTERNS.entrySet()) {
            String type = entry.getKey();
            Pattern pattern = entry.getValue();
            Matcher matcher = pattern.matcher(text);
            
            while (matcher.find()) {
                entities.add(InputProcessResult.NamedEntity.builder()
                        .text(matcher.group())
                        .type(type)
                        .confidence(0.8)
                        .startIndex(matcher.start())
                        .endIndex(matcher.end())
                        .build());
            }
        }
        
        return entities;
    }
    
    /**
     * 语言检测
     */
    private String detectLanguage(String text) {
        // 简化的语言检测
        if (text.matches(".*[\u4e00-\u9fa5]+.*")) {
            return "zh-CN";
        } else if (text.matches(".*[\u3040-\u309f\u30a0-\u30ff]+.*")) {
            return "ja-JP";
        } else {
            return "en-US";
        }
    }
    
    /**
     * 计算文本质量评分
     */
    private Double calculateQualityScore(String text) {
        double score = 0.5; // 基础分
        
        // 长度评分
        int length = text.length();
        if (length > 10 && length < 1000) {
            score += 0.2;
        }
        
        // 完整性评分（包含标点符号）
        if (text.matches(".*[。！？.!?].*")) {
            score += 0.1;
        }
        
        // 多样性评分（词汇丰富度）
        String[] words = text.split("\\s+");
        Set<String> uniqueWords = new HashSet<>(Arrays.asList(words));
        double diversity = (double) uniqueWords.size() / words.length;
        score += diversity * 0.2;
        
        return Math.min(score, 1.0);
    }
}